package com.reny.ll.git.base_logic.di

import com.reny.ll.git.base_logic.MApp
import com.reny.ll.git.base_logic.api.APIConfig
import com.reny.ll.git.base_logic.api.BasicAuthInterceptor
import com.reny.ll.git.base_logic.api.LoggerInterceptor
import com.reny.ll.git.core.App
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import org.kodein.di.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

private const val HTTP_CLIENT_MODULE_TAG = "httpClientModule"
const val HTTP_CLIENT_MODULE_INTERCEPTOR_LOG_TAG = "http_client_module_interceptor_log_tag"
const val HTTP_CLIENT_MODULE_INTERCEPTOR_AUTH_TAG = "http_client_module_interceptor_auth_tag"

const val RETROFIT_MODULE_BASE_TAG = "RETROFIT_MODULE_BASE_TAG"
const val RETROFIT_MODULE_GANK_TAG = "RETROFIT_MODULE_GANK_TAG"

const val TIME_OUT_SECONDS = 10L

val httpClientModule = DI.Module(HTTP_CLIENT_MODULE_TAG) {

    bind<Retrofit.Builder>() with provider { Retrofit.Builder() }

    bind<OkHttpClient.Builder>() with provider { OkHttpClient.Builder() }

    bind<Retrofit>(RETROFIT_MODULE_BASE_TAG) with singleton {
        instance<Retrofit.Builder>()
                .baseUrl(APIConfig.BASE_URL)
                .client(instance())
                .addConverterFactory(GsonConverterFactory.create(MApp.gson))
                .build()
    }

    bind<Retrofit>(RETROFIT_MODULE_GANK_TAG) with singleton {
        instance<Retrofit.Builder>()
            .baseUrl(APIConfig.GANK_URL)
            .client(instance())
            .addConverterFactory(GsonConverterFactory.create(MApp.gson))
            .build()
    }

    bind<Interceptor>(HTTP_CLIENT_MODULE_INTERCEPTOR_LOG_TAG) with singleton {
        LoggerInterceptor()
    }

    bind<Interceptor>(HTTP_CLIENT_MODULE_INTERCEPTOR_AUTH_TAG) with singleton {
        BasicAuthInterceptor()
    }

    bind<OkHttpClient>() with singleton {
        instance<OkHttpClient.Builder>().apply {
            connectTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS)
            writeTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS)
            readTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS)
            addInterceptor(instance<Interceptor>(HTTP_CLIENT_MODULE_INTERCEPTOR_LOG_TAG))
            addInterceptor(instance<Interceptor>(HTTP_CLIENT_MODULE_INTERCEPTOR_AUTH_TAG))
            retryOnConnectionFailure(true)
            if(!App.isDebug) {
                proxy(Proxy.NO_PROXY)//防止代理抓包 isDebug 关闭 可以抓包
            }
            hostnameVerifier { _, _ -> true }
        }.build()
    }
}